<?php
/**
 * an uploaded file
 *
 * This file is part of Webappkit, a packages system for PHP web apps
 * @link http://webappkit.net
 * @package
 * @subpackage
 * @author J.Ducastel <nospam0@ducastel.name>
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 */

/**
 * @property string $key key within form and _FILES
 * @property string $name initial name
 * @property string $tmp_name temporary file's path
 * @property int $size isze in bytes
 * @property int $error error cause
 */
class DjUploadedFile {

    /**
     * load from $_FILES
     * @param string $key within $_FILES
     * @return DjUploadedFile|null
     */
    public static function fromFiles($key) {
        if (!array_key_exists($key, $_FILES)) {
            return null;
        }
        $u = new DjUploadedFile();
        $u->key = $key;
        $u->name = $_FILES[$key]['name'];
        $u->tmp_name = $_FILES[$key]['tmp_name'];
        $u->size = $_FILES[$key]['size'];
        $u->error = $_FILES[$key]['error'];
        return $u;
    }

    /**
     * move to path
     * @param string $path folder
     * @param string $name if null, will keep initial name
     * @return bool
     */
    public function move($path, $name=null) {
        if (is_null($name))
            $name = $this->name;
        $new = realpath($path).$name;
        return rename($this->tmp_name, $new);
    }
}

/*
        UPLOAD_ERR_OK => 'no errors'
        , UPLOAD_ERR_INI_SIZE => 'exceeds max size from php.ini'
        , UPLOAD_ERR_FORM_SIZE => 'exceeds form-defined max size'
        , UPLOAD_ERR_PARTIAL => 'partially uploaded'
        , UPLOAD_ERR_NO_FILE => 'No file was uploaded'
        , UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder'
        , UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk'
        , UPLOAD_ERR_EXTENSION => 'File upload stopped by extension'
*/